<?php
/**
 * WooCommerce Shop Functions
 * WooCommerce商店功能增强
 * 
 * @package WP Bootstrap Woo
 */

defined('ABSPATH') || exit;

/**
 * 添加WooCommerce支持
 */
function wbw_add_woocommerce_support() {
    add_theme_support('woocommerce');
    add_theme_support('wc-product-gallery-zoom');
    add_theme_support('wc-product-gallery-lightbox');
    add_theme_support('wc-product-gallery-slider');
}
add_action('after_setup_theme', 'wbw_add_woocommerce_support');

/**
 * 自定义WooCommerce产品循环
 */
function wbw_custom_product_loop_start() {
    echo '<ul class="products columns-' . wc_get_loop_prop('columns') . '">';
}

function wbw_custom_product_loop_end() {
    echo '</ul>';
}

// 移除默认的产品循环钩子
remove_action('woocommerce_output_content_wrapper', 'woocommerce_output_content_wrapper', 10);
remove_action('woocommerce_output_content_wrapper_end', 'woocommerce_output_content_wrapper_end', 10);

// 添加自定义产品循环钩子
add_action('woocommerce_output_content_wrapper', 'wbw_custom_product_loop_start', 10);
add_action('woocommerce_output_content_wrapper_end', 'wbw_custom_product_loop_end', 10);

/**
 * 修改WooCommerce默认设置
 */
function wbw_modify_woocommerce_defaults() {
    // 修改产品每页显示数量
    return _xin('products_per_page', 12);
}
add_filter('loop_shop_per_page', 'wbw_modify_woocommerce_defaults', 20);

/**
 * 修改产品列数
 */
function wbw_modify_product_columns() {
    return _xin('shop_columns', 4);
}
add_filter('loop_shop_columns', 'wbw_modify_product_columns');

/**
 * 添加产品快速查看按钮
 */
function wbw_add_quick_view_button() {
    global $product;
    echo '<button type="button" class="btn-quick-view" data-product-id="' . $product->get_id() . '" title="Quick View">';
    echo '<i class="feather-eye"></i>';
    echo '</button>';
}
add_action('woocommerce_after_shop_loop_item', 'wbw_add_quick_view_button', 15);

/**
 * 添加愿望清单按钮
 */
function wbw_add_wishlist_button() {
    global $product;
    $user_id = get_current_user_id();
    $wishlist = $user_id ? get_user_meta($user_id, 'wbw_wishlist', true) : array();
    $in_wishlist = is_array($wishlist) && in_array($product->get_id(), $wishlist);
    
    $class = $in_wishlist ? 'btn-wishlist in-wishlist' : 'btn-wishlist';
    $icon = $in_wishlist ? 'feather-heart-filled' : 'feather-heart';
    
    echo '<button type="button" class="' . $class . '" data-product-id="' . $product->get_id() . '" title="Add to Wishlist">';
    echo '<i class="' . $icon . '"></i>';
    echo '</button>';
}
add_action('woocommerce_after_shop_loop_item', 'wbw_add_wishlist_button', 16);

/**
 * 添加比较按钮
 */
function wbw_add_compare_button() {
    global $product;
    echo '<button type="button" class="btn-compare" data-product-id="' . $product->get_id() . '" title="Compare">';
    echo '<i class="feather-shuffle"></i>';
    echo '</button>';
}
add_action('woocommerce_after_shop_loop_item', 'wbw_add_compare_button', 17);

/**
 * 自定义购物车数量按钮
 */
function wbw_custom_quantity_input($args = array(), $product = null, $echo = true) {
    if (is_null($product)) {
        $product = $GLOBALS['product'];
    }
    
    $defaults = array(
        'input_id'     => uniqid('quantity_'),
        'input_name'   => 'quantity',
        'input_value'  => '1',
        'classes'      => apply_filters('woocommerce_quantity_input_classes', array('input-text', 'qty', 'text'), $product),
        'max_value'    => apply_filters('woocommerce_quantity_input_max', -1, $product),
        'min_value'    => apply_filters('woocommerce_quantity_input_min', 0, $product),
        'step'         => apply_filters('woocommerce_quantity_input_step', 1, $product),
        'pattern'      => apply_filters('woocommerce_quantity_input_pattern', has_filter('woocommerce_stock_amount', 'intval') ? '[0-9]*' : ''),
        'inputmode'    => apply_filters('woocommerce_quantity_input_inputmode', has_filter('woocommerce_stock_amount', 'intval') ? 'numeric' : ''),
        'product_name' => $product ? $product->get_title() : '',
        'placeholder'  => apply_filters('woocommerce_quantity_input_placeholder', '', $product),
    );
    
    $args = apply_filters('woocommerce_quantity_input_args', wp_parse_args($args, $defaults), $product);
    
    // Apply sanity to min/max args - min cannot be lower than 0.
    $args['min_value'] = max($args['min_value'], 0);
    $args['max_value'] = 0 < $args['max_value'] ? $args['max_value'] : '';
    
    if ('' !== $args['max_value'] && $args['max_value'] < $args['min_value']) {
        $args['max_value'] = $args['min_value'];
    }
    
    ob_start();
    ?>
    <div class="quantity-wrapper">
        <button type="button" class="qty-btn qty-decrease">-</button>
        <input
            type="number"
            id="<?php echo esc_attr($args['input_id']); ?>"
            class="<?php echo esc_attr(join(' ', (array) $args['classes'])); ?>"
            name="<?php echo esc_attr($args['input_name']); ?>"
            value="<?php echo esc_attr($args['input_value']); ?>"
            aria-label="<?php echo esc_attr_x('Product quantity', 'Product quantity input tooltip', 'woocommerce'); ?>"
            size="4"
            min="<?php echo esc_attr($args['min_value']); ?>"
            max="<?php echo esc_attr(0 < $args['max_value'] ? $args['max_value'] : ''); ?>"
            <?php if (! empty($args['step'])) : ?>
                step="<?php echo esc_attr($args['step']); ?>"
            <?php endif; ?>
            placeholder="<?php echo esc_attr($args['placeholder']); ?>"
            inputmode="<?php echo esc_attr($args['inputmode']); ?>"
            autocomplete="off" />
        <button type="button" class="qty-btn qty-increase">+</button>
    </div>
    <?php
    
    if ($echo) {
        echo ob_get_clean();
    } else {
        return ob_get_clean();
    }
}

/**
 * 自定义产品标签
 */
function wbw_custom_sale_flash($html, $post, $product) {
    if ($product->is_on_sale()) {
        if ($product->get_type() === 'variable') {
            $html = '<span class="onsale">Sale</span>';
        } else {
            $regular_price = (float) $product->get_regular_price();
            $sale_price = (float) $product->get_sale_price();
            
            if ($regular_price > 0) {
                $percentage = round((($regular_price - $sale_price) / $regular_price) * 100);
                $html = '<span class="onsale">-' . $percentage . '%</span>';
            } else {
                $html = '<span class="onsale">Sale</span>';
            }
        }
    }
    
    return $html;
}
add_filter('woocommerce_sale_flash', 'wbw_custom_sale_flash', 10, 3);

/**
 * 添加"新品"标签
 */
function wbw_add_new_product_badge() {
    global $product;
    
    $new_days = _xin('new_product_days', 30);
    $created_date = strtotime($product->get_date_created());
    $current_date = time();
    $days_diff = ($current_date - $created_date) / (60 * 60 * 24);
    
    if ($days_diff <= $new_days && !$product->is_on_sale()) {
        echo '<span class="new-badge">New</span>';
    }
}
add_action('woocommerce_before_shop_loop_item_title', 'wbw_add_new_product_badge', 15);

/**
 * 自定义购物车图标
 */
function wbw_custom_cart_link() {
    $cart_count = WC()->cart->get_cart_contents_count();
    $cart_url = wc_get_cart_url();
    
    echo '<a href="' . esc_url($cart_url) . '" class="cart-icon">';
    echo '<i class="feather-shopping-cart"></i>';
    echo '<span class="cart-count">' . $cart_count . '</span>';
    echo '</a>';
}

/**
 * Ajax更新购物车片段
 */
function wbw_add_to_cart_fragment($fragments) {
    $cart_count = WC()->cart->get_cart_contents_count();
    
    $fragments['.cart-count'] = '<span class="cart-count">' . $cart_count . '</span>';
    $fragments['.cart-counter'] = '<span class="cart-counter">(' . $cart_count . ')</span>';
    
    return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'wbw_add_to_cart_fragment');

/**
 * 自定义结账字段
 */
function wbw_custom_checkout_fields($fields) {
    // 重新排序账单字段
    $billing_fields_order = array(
        'billing_first_name',
        'billing_last_name',
        'billing_company',
        'billing_email',
        'billing_phone',
        'billing_country',
        'billing_address_1',
        'billing_address_2',
        'billing_city',
        'billing_state',
        'billing_postcode'
    );
    
    foreach ($billing_fields_order as $field) {
        if (isset($fields['billing'][$field])) {
            $ordered_fields[$field] = $fields['billing'][$field];
        }
    }
    
    $fields['billing'] = $ordered_fields;
    
    return $fields;
}
add_filter('woocommerce_checkout_fields', 'wbw_custom_checkout_fields');

/**
 * 添加自定义WooCommerce页面类
 */
function wbw_add_woocommerce_body_class($classes) {
    if (is_woocommerce() || is_cart() || is_checkout() || is_account_page()) {
        $classes[] = 'woocommerce-page';
    }
    
    if (is_shop()) {
        $classes[] = 'shop-page';
    }
    
    if (is_product()) {
        $classes[] = 'single-product-page';
    }
    
    if (is_cart()) {
        $classes[] = 'cart-page';
    }
    
    if (is_checkout()) {
        $classes[] = 'checkout-page';
    }
    
    if (is_account_page()) {
        $classes[] = 'account-page';
    }
    
    return $classes;
}
add_filter('body_class', 'wbw_add_woocommerce_body_class');

/**
 * 禁用WooCommerce默认样式
 */
if (_xin('disable_woocommerce_styles', true)) {
    add_filter('woocommerce_enqueue_styles', '__return_empty_array');
}

/**
 * 移除WooCommerce生成器
 */
remove_action('wp_head', 'wc_generator_tag');

/**
 * 自定义面包屑
 */
function wbw_custom_breadcrumbs() {
    if (function_exists('woocommerce_breadcrumb')) {
        woocommerce_breadcrumb(array(
            'delimiter'   => ' / ',
            'wrap_before' => '<nav class="woocommerce-breadcrumb breadcrumb">',
            'wrap_after'  => '</nav>',
            'before'      => '<span>',
            'after'       => '</span>',
            'home'        => _x('Home', 'breadcrumb', 'woocommerce'),
        ));
    }
}
